package com.ansion.baseui.base.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Outline;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewOutlineProvider;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.ansion.baseui.R;
import com.ansion.baseui.base.util.UserFaceUtil;
import com.ansion.constant.BConstant;
import com.ansion.log.VLog;
import com.ansion.user.UserSdkFactory;
import com.ansion.user.listener.ContactChangeListener;
import com.ansion.utils.ContactUtil;
import com.ansion.utils.ResourceUtils;
import com.ansion.utils.ThreadUtil;
import com.ansion.utils.UiUtils;
import com.facebook.common.util.UriUtil;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.backends.pipeline.PipelineDraweeControllerBuilder;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;

/**
 * @author john 2022/03/03
 * @desc 通用头像加载view，自带用户头像变更监听
 * 备注：如果仅需要加载图片，请直接调用非bindUid方法；如果不需要圆角显示，请在xml中添加app:is_circle="false"
 */
public class UserFaceView extends LinearLayout {
    private String TAG = "UserFaceView";
    private ContactChangeListener contactChangeListener;
    private String tag2;
    private boolean isCircle = false;
    private boolean showCorner = true;

    private boolean isGroupCall = false;

    private float cornerRadius;
    //默认圆角10dp
    private final int DEFAULT_RADIUS = 10;

    //头像
    private SimpleDraweeViewFix imageView;
    private int Default_Text_Size = 16;
    //默认字母头像大小18dp
    private int displayTextSize = Default_Text_Size;

    private TextView tvDisplayText;

    //暂时留着，后续可能会变更默认头像显示规则
    private String displayText = null;
    //自定义placeHolder，默认用户的是字母头像，群的是是群默认头像
    private int placeHolder = 0;
    private int size = BConstant.Fresco.defaultAvatarSize;

    public UserFaceView(Context context) {
        super(context);
        initAttr(null);
    }

    public UserFaceView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initAttr(attrs);
    }

    public UserFaceView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAttr(attrs);
    }

    private void initAttr(@Nullable AttributeSet attrs) {
        View container = LayoutInflater.from(getContext()).inflate(
                R.layout.user_face_layout, null);
        LayoutParams param = new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
        addView(container, param);
//        vipIcon = container.findViewById(R.id.vip_icon);
        imageView = container.findViewById(R.id.simple_draweeView);

        tvDisplayText = container.findViewById(R.id.tv_display_text);

        if (attrs != null) {
            TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.UserFaceView);
            //默认圆角为8dp
            if (!isInEditMode()) {
                cornerRadius = typedArray.getDimension(R.styleable.UserFaceView_corner_radius, UiUtils.dp(DEFAULT_RADIUS));
            }
            isCircle = typedArray.getBoolean(R.styleable.UserFaceView_is_circle, false);
            showCorner = typedArray.getBoolean(R.styleable.UserFaceView_show_corner, true);
            displayTextSize = typedArray.getInt(R.styleable.UserFaceView_face_text_size, Default_Text_Size);
            typedArray.recycle();
        } else {
            cornerRadius = UiUtils.dp(DEFAULT_RADIUS);
        }
        tvDisplayText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, displayTextSize);
        if (showCorner) {
            drawCornerRadius();
        }

    }

    public void setCornerRadius(int radius) {
        cornerRadius = radius;
        drawCornerRadius();
    }

    public void setDisplayTextSize(int size) {
        displayTextSize = size;
        tvDisplayText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, displayTextSize);
    }

    private void drawCornerRadius() {

        imageView.setOutlineProvider(new ViewOutlineProvider() {
            @Override
            public void getOutline(View view, Outline outline) {
                if (view.getWidth() == 0 || view.getHeight() == 0)
                    return;
                int padding = getPaddingStart();
                float radius = cornerRadius;
                if (isCircle) {
                    radius = Math.min(view.getWidth(), view.getHeight()) / 2f - padding;
                }
                outline.setRoundRect(padding, padding, view.getWidth() - padding, view.getHeight() - padding, radius);
            }
        });
        imageView.setClipToOutline(true);

    }

    public void bindUid(@NonNull String userUid) {
        bindUid(userUid, false);
    }

    public void bindUid(@NonNull String userUid, boolean useOriginalAvatar) {
        reset();
        if (TextUtils.isEmpty(userUid)) {
            imageView.setImageResource(R.drawable.b_ic_user_avatar_default_blue_no_radius);
            return;
        }
        if (VLog.OPEN_LOG) {
            VLog.d(TAG, "bindUid:" + userUid);
        }
        if (ContactUtil.isLocalServerId(userUid)) {
            loadDefAvatar(userUid);
            init(userUid, useOriginalAvatar, false);
        } else {
            init(userUid, useOriginalAvatar, true);
            loadAvatar(userUid, useOriginalAvatar);
        }
    }


    private void reset() {
        isGroupCall = false;
        size = BConstant.Fresco.defaultAvatarSize;
        placeHolder = 0;
        clearDisplayText();
    }

    private void clearDisplayText() {
        tvDisplayText.setText(null);
    }

    public void bindUid(@NonNull String userUid, int avatarDrawable) {
        bindUid(userUid, false, avatarDrawable);

    }

    public void bindUid(@NonNull String userUid, boolean isGroupCall, int avatarDrawable) {
        bindUid(userUid, false, isGroupCall, avatarDrawable);
    }

    public void bindUid(@NonNull String userUid, boolean useOriginalAvatar, boolean isGroupCall, int avatarDrawable) {
        reset();
        this.isGroupCall = isGroupCall;
        init(userUid, useOriginalAvatar, true);
        placeHolder = avatarDrawable;
        loadAvatar(userUid, useOriginalAvatar);
    }

    public void bindUidWithSize(@NonNull String userUid, boolean useOriginalAvatar, int avatarDrawable, int size) {
        reset();
        this.size = size;
        init(userUid, useOriginalAvatar, true);
        placeHolder = avatarDrawable;
        loadAvatar(userUid, useOriginalAvatar);
    }

    private void setImageURIWithThumb(Uri uri, boolean withThumb) {//头像控件默认使用小图
        VLog.i(TAG, "setImageURIWithThumb 0,id:%s", uri);
        boolean isNormalSession = ContactUtil.isNormalSession(getTag2());
        //老版本使用老的磁盘DEFAULT缓存，新版本使用SMALL缓存
        ImageRequest.CacheChoice imageChoice = ImageRequest.CacheChoice.SMALL;
        if (!isNormalSession) {//广告UID，则使用MainCache
            imageChoice = ImageRequest.CacheChoice.DEFAULT;
        }
        if (VLog.OPEN_LOG) {
            VLog.d("TAG_IMAGE_LOAD", "load for [%s] uri:%s use cache:%s", this.getTag2(), uri.toString(), imageChoice);
        }
        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                //根据View的尺寸放缩图片
                .setResizeOptions(new ResizeOptions(size, size))
                .setCacheChoice(imageChoice)
                .build();
        PipelineDraweeControllerBuilder builder = Fresco.newDraweeControllerBuilder();
        builder
                .setOldController(imageView.getController())
                .setImageRequest(request)
                .setControllerListener(new BaseControllerListener() {
                    @Override
                    public void onFinalImageSet(String id, Object imageInfo, Animatable animatable) {
                        super.onFinalImageSet(id, imageInfo, animatable);
                        VLog.i(TAG, "onFinalImageSet 0,id:%s,uid:%s", id, getTag2());
                        //图片设置成功
                        clearDisplayText();
                    }

                    @Override
                    public void onIntermediateImageSet(String id, Object imageInfo) {
                        super.onIntermediateImageSet(id, imageInfo);
                        VLog.i(TAG, "onFinalImageSet 1,id:%s,uid:%s", id, getTag2());
                        //图片设置成功
                        clearDisplayText();
                    }

                    @Override
                    public void onFailure(String id, Throwable throwable) {
                        super.onFailure(id, throwable);
                        //图片加载失败
                        VLog.i(TAG, "onFailure 0,id:%s,uid:%s", id, getTag2());

                    }

                    @Override
                    public void onIntermediateImageFailed(String id, Throwable throwable) {
                        super.onIntermediateImageFailed(id, throwable);
                        //图片加载失败
                        VLog.i(TAG, "onIntermediateImageFailed,id:%s,uid:%s", id, getTag2());
                    }

                    @Override
                    public void onRelease(String id) {
                        super.onRelease(id);
                        VLog.i(TAG, "onRelease,id:%s,uid:%s", id, getTag2());
                    }
                })
                .setCallerContext(uri);
        if (withThumb) {
            int thumbSize = BConstant.Fresco.defaultAvatarSize;
            ImageRequest thumbRequest = ImageRequestBuilder.newBuilderWithSource(uri)
                    //根据View的尺寸放缩图片
                    .setResizeOptions(new ResizeOptions(thumbSize, thumbSize))
                    .setCacheChoice(imageChoice)
                    .build();
            builder.setLowResImageRequest(thumbRequest);
        }
        imageView.setController(builder.build());

    }


    public void bindDrawable(int avatarDrawable) {
        removeListener();
        clearDisplayText();
        imageView.setImageResource(avatarDrawable);
    }

    public void bindDrawable(Drawable avatarDrawable) {
        removeListener();
        imageView.setImageDrawable(avatarDrawable);
    }

    public void bindBitmap(Bitmap bitmap) {
        removeListener();
        clearDisplayText();
        imageView.setImageBitmap(bitmap);
    }

    public void bindTextAvatar(String uid, String text) {
        removeListener();
        clearDisplayText();
        tvDisplayText.setText(text);
        setUserTxtAvatarResource(uid);
    }


    public void bindUrl(@NonNull String userId, @Nullable String url, int avatarDrawable) {
        reset();
        init(userId, false, false);
        if (VLog.OPEN_LOG) {
            VLog.d(TAG, "bindUrl for:" + userId);
        }
        if (TextUtils.isEmpty(url)) {
            imageView.setImageResource(avatarDrawable);
        } else {
            if (avatarDrawable != 0) {
                setDefaultAvatarResource(avatarDrawable);
            }
            loadAvatarFromUrl(url);
        }

    }

    public void bindUrl(@NonNull String userId, @Nullable String url, Drawable avatarDrawable) {
        reset();
        init(userId, false, false);
        if (VLog.OPEN_LOG) {
            VLog.d(TAG, "bindUrl1 for:" + userId);
        }
        if (TextUtils.isEmpty(url)) {
            imageView.setImageDrawable(avatarDrawable);
        } else {
            if (avatarDrawable != null) {
                setDefaultAvatarResource(avatarDrawable);
            }
            loadAvatarFromUrl(url);
        }
    }


    private void init(@NonNull String userUid, boolean useOriginalAvatar, boolean regListener) {
        if (TextUtils.isEmpty(userUid)) {
            return;
        }
        setTag2(userUid);
        if (regListener) {
            initListener(userUid, useOriginalAvatar);
//            UserSdkFactory.getSdk().registerContactListener(contactChangeListener);
        } else {
            removeListener();
        }
    }

    private void removeListener() {
        if (contactChangeListener != null) {
//            UserSdkFactory.getSdk().unregisterContactListener(contactChangeListener);
        }
    }

    private void initListener(String userUid, boolean useOriginalAvatar) {
        if (contactChangeListener == null) {
            contactChangeListener = new ContactChangeListener() {


                @Override
                public void onFaceChanged(@NonNull String uid, @NonNull String avatar) {
                    if (VLog.OPEN_LOG) {
                        VLog.d(TAG, "on  avatar change for user:" + uid + ",avatar:" + avatar);
                    }
                    if (!TextUtils.equals(uid, UserFaceView.this.getTag2())) {
                        return;
                    }
                    ThreadUtil.runUiSafely(getContext(), () -> {
                        if (!TextUtils.equals(uid, UserFaceView.this.getTag2())) {
                            return;
                        }
                        if (!TextUtils.isEmpty(avatar)) {
                            //有头像的时候设置成默认用户头像
//                            int index = UserFaceUtil.getRandomIndex(uid);
//                            setDefaultAvatarResource(UserFaceUtil.userAvatarResource[index]);
//                            clearDisplayText();

//                            loadAvatarFromUrl(avatar);

                            VLog.i(TAG, "onFaceChanged load avatar for group call,%s", uid);
                            if (isGroupCall) {
                                loadAvatarFromUrl(avatar);
                            } else {
                                loadAvatar(uid, useOriginalAvatar);
                            }

                        } else {//没头像且之前就是字母头像则不做变更，如果没有字母头像则重新生成字母头像

                            VLog.d(TAG, "onFaceChanged but avatar is null,call loadAvatar");
                            loadAvatar(uid, useOriginalAvatar);
//                            if (TextUtils.isEmpty(tvDisplayText.getText())) {//头像从有到无，之前是正常头像，则重新调用loadAvatar
//
//                            }
                        }
                    });
                }
            };
        }
        contactChangeListener.init(userUid);
    }


    protected void loadAvatarFromUrl(String avatarUrl) {
        //如果图片尺寸大于200则默认启用thumb图
        boolean withThumb = size > BConstant.Fresco.defaultAvatarSize;
        Uri uri = UriUtil.parseUriOrNull(avatarUrl);
        if (uri != null) {
            setImageURIWithThumb(uri, withThumb);
        }
    }

    private void loadAvatar(String userId, boolean useOriginalAvatar) {
        if (VLog.OPEN_LOG) {
            VLog.d(TAG, "load loadDefAvatar1 for user:%s,placeHolder:%d", userId, placeHolder);
        }
        if (ContactUtil.isLocalServerId(userId)) {
            imageView.setImageResource(getPlaceHolder(userId));
            return;
        }

        //setPlaceholderImage是为了兼容外部设置placeHolder

        if (placeHolder != 0) {//先换
            setDefaultAvatarResource(placeHolder);
        } else {
            if (ContactUtil.isOAAccount(userId)) {//直接设置placeHolder
                //给botim官方账号兜底
                setDefaultAvatarResource(getPlaceHolder(userId));
            } else if (ContactUtil.isGroup(userId)) {
                int defaultAvatar = UserFaceUtil.getGroupDefaultAvatarResource(userId);
                setDefaultAvatarResource(defaultAvatar);
            } else if (ContactUtil.isUser(userId)) {
                setUserTxtAvatarResource(userId);
            }
        }


        UserSdkFactory.getSdk().getContactInfo(userId, false, useOriginalAvatar, contactInfo -> {
            if (contactInfo == null)
                return;

            if (!TextUtils.equals(userId, contactInfo.getUid())) {
                return;
            }
            ThreadUtil.runUiSafely(getContext(), () -> {
                if (!TextUtils.equals(contactInfo.getUid(), UserFaceView.this.getTag2())) {
                    return;
                }
                if (VLog.OPEN_LOG) {
                    VLog.d(TAG, "load avatar for user:" + userId + ",avatar:" + contactInfo.getAvatarUrl());
                }
                if (placeHolder == 0) {
                    if (ContactUtil.isUser(contactInfo.getUid())) {//没有头像，设置字母头像
                        if (!contactInfo.isAppUser()) {//非app用户直接设成蓝色小人
                            clearDisplayText();
                            setDefaultAvatarResource(R.drawable.b_ic_user_avatar_default_blue_no_radius);
                        } else {
                            displayText = contactInfo.getAvatarDisplayText();
                            VLog.d(TAG, "tvDisplayText setText:%s,uid:%s", displayText, contactInfo.getUid());
                            tvDisplayText.setText(displayText);
                        }

//                        int index = UserFaceUtil.getRandomIndex(userId);
//                        setDefaultAvatarResource(UserFaceUtil.userAvatarBackgroundResource[index]);
                    }
                }

                //设置自定义头像
                if (!TextUtils.isEmpty(contactInfo.getAvatarUrl())) {//有头像
                    loadAvatarFromUrl(contactInfo.getAvatarUrl());
                } else {//设置空头像，避免头像复用问题
                    //设置用户和群组的placeHolder
                    setImageURIWithThumb(Uri.EMPTY, false);


                }

            });
        });
    }

    private void setUserTxtAvatarResource(String userId) {
        int index = UserFaceUtil.getRandomIndex(userId);
        setDefaultAvatarResource(UserFaceUtil.userAvatarBackgroundResource[index]);
        tvDisplayText.setTextColor(ResourceUtils.getColor(UserFaceUtil.userNameColor[index]));
    }

    private void setDefaultAvatarResource(int drawableResource) {
        imageView.getHierarchy().setPlaceholderImage(drawableResource);
//        imageView.getHierarchy().setFailureImage(drawableResource);
    }

    private void setDefaultAvatarResource(Drawable drawable) {
        imageView.getHierarchy().setPlaceholderImage(drawable);
//        imageView.getHierarchy().setFailureImage(drawable);
    }

    private void loadDefAvatar(String uid) {
        if (VLog.OPEN_LOG) {
            VLog.d(TAG, "load loadDefAvatar for user:" + uid);
        }
        imageView.setImageResource(getPlaceHolder(uid));
    }

    protected int getPlaceHolder(String uid) {
        int defAvatar = R.drawable.b_ic_user_avatar_default_blue_no_radius;
        if (ContactUtil.isGroup(uid)) {
            defAvatar = R.drawable.b_ic_group_avatar_default_blue_no_radius;
        }else if (ContactUtil.isBotimTeam(uid)) {//isBotimTeam一定要放在isOAAccount之前
            defAvatar = R.drawable.b_ic_app_logo_no_radius;
        } else if (ContactUtil.isOAAccount(uid)) {
            defAvatar = R.drawable.b_avatar_load_fail;
        } else if (ContactUtil.isFileAssistant(uid)) {
            defAvatar = R.drawable.b_ic_file_transfer_no_radius;
        }
        return defAvatar;
    }


    @Override
    protected void onAttachedToWindow() {
        if (contactChangeListener != null) {
            UserSdkFactory.getSdk().registerContactListener(contactChangeListener);
        }
        super.onAttachedToWindow();
    }

    @Override
    protected void onDetachedFromWindow() {
        if (contactChangeListener != null) {
            UserSdkFactory.getSdk().unregisterContactListener(contactChangeListener);
        }
        super.onDetachedFromWindow();
    }

    public String getTag2() {
        return tag2;
    }

    public void setTag2(String tag2) {
        this.tag2 = tag2;
    }

    public SimpleDraweeViewFix getImageView() {
        return imageView;
    }
}
